
<template>
  <div class="register-wrap">
      <div class="ms-register">
          <div class="ms-title">IWu招聘</div>
          <el-form :model="registerUser" :rules="registerRules" ref="registerForm" label-width="0px"
              class="ms-content">
              <el-form-item prop="name">
                  <el-input v-model="registerUser.name" placeholder="请输入你的用户名" :prefix-icon="User">
                  </el-input>
              </el-form-item>
              <el-form-item prop="email">
                  <el-input v-model="registerUser.email" placeholder="请输入邮箱" :prefix-icon="Message">
                  </el-input>
              </el-form-item>
              <el-form-item prop="password_1">
                  <el-input type="password" placeholder="请输入密码" v-model="registerUser.password_1"
                      @keyup.enter.native="handleRegister(registerForm)" :prefix-icon="Lock">
                  </el-input>
              </el-form-item>
              <el-form-item prop="password_2">
                  <el-input type="password" placeholder="请再次输入密码" v-model="registerUser.password_2"
                      @keyup.enter.native="handleRegister(registerForm)" :prefix-icon="Lock">
                  </el-input>
              </el-form-item>
              <el-form-item prop="code_1">
          <div class="codeItem">
            <el-input type="text" style="width: 230px;" v-model="registerUser.code_1" placeholder="请输入验证码" />
            <!-- <template v-slot="suffix"> -->
            <div class="codePicture" @click="refreshCode">
              <CanvasCode class="codePicture1" :identifyCode="codeData.identifyCode"></CanvasCode>
            </div>
          </div>

          <!-- </template> -->
        </el-form-item>
              <el-form-item v-if="showENames"  prop="eName">
                  <el-select v-model="registerUser.eName" :multiple="false" filterable allow-create
                      default-first-option 
                      :reserve-keyword="false" 
                      placeholder="请输入你任职的公司"
                      :fit-input-width="true"
                      style="width: 100%;"
                      >
                      <el-option v-for="item in es" :key="item.eId" :label="item.eName" :value="item.eName" />
                  </el-select>
              </el-form-item>
              <el-form-item label="">
                  <el-radio-group v-model="registerUser.role">
                      <el-radio label="user">个人</el-radio>
                      <el-radio label="enterprise">企业</el-radio>
                  </el-radio-group>
              </el-form-item>
              <div class="register-btn">
                  <el-button type="primary" @click="handleRegister(registerForm)">注册</el-button>
              </div>
              <!-- 注册 -->
              <p class="register-tips">Tips : 已有账号? <a href="/login">登录</a></p>
          </el-form>
      </div>
  </div>
</template>
<script lang='ts'>
import { Lock, Message, User } from "@element-plus/icons-vue"
import { reactive, ref, computed, watch,onBeforeMount } from 'vue'
import { getAllE,register } from "@/api/authApi"
import { registerUser, registerRules, } from "@/utills/registerValidators";
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus';
import { useStore } from "vuex"
import {elmessage} from "@/hook/hook"

import { useRoute, useRouter } from 'vue-router';

export default {
  name: 'Register',
  setup() {

    const store = useStore()
    // @ts-ignore
    // const { proxy } = getCurrentInstance() // 1.获取proxy实例
    // 注册方法
    const registerForm = ref<FormInstance>();

    const router = useRouter()

    const showENames = ref(false)
    interface e {
      eId: string
      eName: string

    }
    const es: e[] = reactive([])

    const getRole = computed(() => registerUser.role)
    watch(getRole, (newval, old) => {
      if (getRole.value == "enterprise") {
        
        getAllE().then((res: any) => {
          if (es.length==0){
            es.push(...res.data)
          }
          showENames.value = true
          // console.log(res.data);
        })
      } else {
        showENames.value = false
      }
    })
    const codeData = reactive({
      identifyCodes: '1234567890abcdefjhijk1234567890linopqrsduvwxyz', // 验证码组成元素
      identifyCode: '', // 验证码生成结果
      code: '', // 验证码输入内容
    })
    // 重置验证码
    const refreshCode = () => {
      codeData.identifyCode = ''
      makeCode(codeData.identifyCodes, 4)
      registerUser.code_2=codeData.identifyCode
      // console.log(data.identifyCode);

    }
    const makeCode = (o: any, l: any) => {
      // o代表随机数元素集合，l代表验证码位数（现在为4位验证码）
      for (let i = 0; i < l; i++) {
        codeData.identifyCode += codeData.identifyCodes[randomNum(0, codeData.identifyCodes.length)]
      }

    }
    const randomNum = (min: number, max: number) => {
      return Math.floor(Math.random() * (max - min) + min)
    }
    // 触发登录方法  async异步
    const handleRegister = async (form: FormInstance | undefined) => {
      if(!form) return
      // 点击按钮触发表单验证
      form.validate((valid: any) => {
        if (valid) {
          // 表单数据解构成字典
          const data = {
            ...registerUser
          }
          console.log(data);
          
          register(data)
            .then((res: any) => {
              // console.log(res.data);
              if (res.data["type"] === "success") {
                // console.log(res);
                // 注册成功跳转登录页面
                elmessage(res.data["message"], res.data["type"])
                setTimeout(() => {
                  router.push("/login")
                }, 1000);
              }
              else {
                elmessage(res.data["message"], res.data["type"])
              }
            }

            )
        } else {
          // console.log("error submit!");
          return false;
        }
      });
    };

    onBeforeMount(() => {
      refreshCode()
    })

    

    return {
      Lock, Message, User,
      registerUser,
      registerRules,
      registerForm,
      showENames,
      es,
      codeData,
      refreshCode,
      // value,
      handleRegister,
      

    }
  }
}
</script>
<style lang="css" scoped>
a:hover {
    text-decoration: underline !important;
}
a{
  text-decoration: none;
}
.register-wrap {
    position: relative;
    width: 100vw;
    height: 100vh;
    background-size: cover;
    background-image: url("@/assets/loginRegister/registerBg.jpeg");

}

.ms-title {
    width: 100%;
    line-height: 50px;
    text-align: center;
    font-size: 20px;
    color: #000;
    border-bottom: 1px solid #ddd;
}

.ms-register {
    position: absolute;
    left: 50%;
    top: 42%;
    width: 400px;
    margin: -190px 0 0 -175px;
    border-radius: 5px;
    background: rgba(255, 255, 255, 0.2);
    overflow: hidden;
}

.ms-content {
    padding: 30px 30px;
}

.register-btn {
    text-align: center;
}

.register-btn button {
    width: 100%;
    height: 36px;
    margin-bottom: 10px;
}

.register-tips {
    font-size: 13px;
    line-height: 30px;
    color: #fff;
}
.codeItem {
  width: 340px;
  /* display: inline-flex; */
  float: auto;
}

.codePicture {
  width: 100px;
  height: 30px;
  text-align: center;
  float: right;
  
  border: 2px solid #009199;
}

.codePicture1 {
  float: right;
  width: 100px;
  height: 30px;
}
</style>